package com.example.ssmxuankeback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ssmxuankeback.common.RestBean;
import com.example.ssmxuankeback.dto.ClassDTO;
import com.example.ssmxuankeback.dto.ClassPageQueryDTO;
import com.example.ssmxuankeback.entity.Classes;
import com.example.ssmxuankeback.exception.BusinessException;
import com.example.ssmxuankeback.interfaces.IClassMapper;
import com.example.ssmxuankeback.mapper.ClassMapper;
import com.example.ssmxuankeback.service.ClassService;
import com.example.ssmxuankeback.service.UserService;
import com.example.ssmxuankeback.vo.ClassVO;
import com.example.ssmxuankeback.vo.PageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ClassServiceImpl implements ClassService {

    @Autowired
    ClassMapper classMapper;
    @Autowired
    UserService userService;

    @Override
    public RestBean<ClassVO> getClassByClassId(Long classId) {
        Classes entity = classMapper.selectById(classId);
        if (entity == null) {
            throw new BusinessException("班级不存在");
        }
        return RestBean.success(convertToVO(entity));
    }

    @Override
    public RestBean<ClassVO> addClass(ClassDTO dto) {
        // 检查班级名称是否已存在
        LambdaQueryWrapper<Classes> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Classes::getClassName, dto.getClassName());
        if (classMapper.selectCount(wrapper) > 0) {
            throw new BusinessException("班级名称已存在");
        }

        Classes entity = IClassMapper.INSTANCT.dtoToEntity(dto);
        classMapper.insert(entity);
        return RestBean.success(convertToVO(entity));
    }

    @Override
    public RestBean<ClassVO> updateClass(ClassDTO dto) {
        // 校验班级ID是否存在
        Classes existing = classMapper.selectById(dto.getClassId());
        if (existing == null) {
            throw new BusinessException("班级不存在");
        }

        // 更新操作
        Classes entity = convertToEntity(dto);
        classMapper.updateById(entity);
        return RestBean.success(convertToVO(entity));
    }

    @Override
    public RestBean<ClassVO> deleteClassById(Long classId) {
        // 检查班级是否存在
        Classes entity = classMapper.selectById(classId);
        if (entity == null) {
            throw new BusinessException("班级不存在");
        }

        // 检查是否存在关联学生
        if (userService.hasStudentsInClass(classId)) {
            throw new BusinessException("班级下存在学生，无法删除");
        }

        // 执行删除
        classMapper.deleteById(classId);
        return RestBean.success(convertToVO(entity));
    }

    @Override
    public RestBean<PageVO<ClassVO>> listByPage(ClassPageQueryDTO queryDTO) {
        // 构建分页参数
        Page<Classes> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Classes> wrapper = new LambdaQueryWrapper<>();
        // 模糊查询班级名称
        if (StringUtils.hasText(queryDTO.getClassName())) {
            wrapper.like(Classes::getClassName, queryDTO.getClassName());
        }
        // 排序逻辑
        if (StringUtils.hasText(queryDTO.getSortBy())) {
            String order = "asc".equalsIgnoreCase(queryDTO.getSortOrder()) ? "ASC" : "DESC";
            wrapper.orderBy(true, "asc".equalsIgnoreCase(order), getSortField(queryDTO.getSortBy()));
        }

        // 执行分页查询
        IPage<Classes> pageResult = classMapper.selectPage(page, wrapper);

        // 转换为VO列表
        List<ClassVO> voList = pageResult.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        // 构建分页结果
        PageVO<ClassVO> pageVO = PageVO.<ClassVO>builder()
                .total(pageResult.getTotal())
                .pages(pageResult.getPages())
                .records(voList)
                .build();

        return RestBean.success(pageVO);
    }

    // -------------------- 工具方法 --------------------
    private ClassVO convertToVO(Classes entity) {
        return IClassMapper.INSTANCT.entityToVO(entity);
    }

    private Classes convertToEntity(ClassDTO dto) {
        return IClassMapper.INSTANCT.dtoToEntity(dto);
    }

    /**
     * 安全获取排序字段（防止SQL注入）
     */
    private SFunction<Classes, ?> getSortField(String sortBy) {
        if (sortBy.equalsIgnoreCase("classname")) {
            return Classes::getClassName;
        }
        return Classes::getClassId; // 默认按ID排序
    }
}